﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tecnicas.CasoEstudio.Back.Dominio;
using Tecnicas.CasoEstudio.Repositorio;


namespace Tecnicas.CasoEstudio.Back.Persistencia
{
    public class PersonaDataMapper : AbstractDataMapper
    {
        public PersonaDataMapper()
        {             
        }
        

        public override object Insert(DomainObject obj)
        {
            if (typeof(Persona) != obj.GetType())
                throw new ApplicationException("Este mapper solo opera con objetos del tipo Persona");

            if (obj.PersistenceId == null)
            {
                obj.PersistenceId = RepositorioVersionado.Instance.GetNextKey();
                obj.PersistenceVersion = 0;
            }

            Persona persona = (Persona)obj;

            // se persisten las agregaciones
            MailDataMapper mailDataMapper = new MailDataMapper();
            Mail mail = (Mail)mailDataMapper.Insert(persona.Mail);
            persona.PersistenceIdMail = mail.PersistenceId;


            Persona personaCopia = this.ClonePlainObject(persona);

            RepositorioVersionado.Instance.Guardar(personaCopia, personaCopia.PersistenceId, personaCopia.PersistenceVersion, ++personaCopia.PersistenceVersion);

            persona.Mail.PersistenceId = mail.PersistenceId;
            persona.Mail.PersistenceVersion = mail.PersistenceVersion;

            persona.PersistenceVersion++;
            return persona;
        }

        private Persona ClonePlainObject(Persona persona)
        {            
            Persona personaCopia = new Persona();
            personaCopia.PersistenceId = persona.PersistenceId;
            personaCopia.PersistenceVersion = persona.PersistenceVersion;
            personaCopia.PersistenceIdMail = persona.PersistenceIdMail;
            
            personaCopia.Nombre = persona.Nombre;
            return personaCopia;
        }

        public override void Delete(long? id, object version)
        {
            RepositorioVersionado.Instance.Eliminar(typeof(Persona), id, version);
        }
        public override void Delete(DomainObject obj)
        {
            this.Delete(obj.PersistenceId, obj.PersistenceVersion);
        }

        public override DomainObject Find(long? id)
        {
            return (Persona)RepositorioVersionado.Instance.ObtenerPorId(typeof(Persona), id);
        }

       
    }
}
